package git.soulbgm.ximalaya;

import git.soulbgm.jd.JdApplication;
import git.soulbgm.utils.PropertiesUtil;
import git.soulbgm.utils.StringUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 应用程序
 *
 * @author HRJ
 * @date 2021/07/23
 */
public class XimalayaApplication {

    private static WebDriver driver;
    private static ChromeOptions options;
    private static String baseUrl = "https://www.ximalaya.com/youshengshu/12169061/";
    private static String filePath = "D:/output/一念永恒标题.txt";

    /**
     * 判断运行时是否是以jar运行
     *
     * @return boolean
     */
    private static boolean isJar(String path) {
        File file = new File(path);
        return file.isFile();
    }

    /**
     * 检测环境
     */
    private static void detectionEnvironment() throws IOException {
        String path = JdApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String configFilePath = "config.properties";
        if (isJar(path)) {
            path = path.substring(0, path.lastIndexOf(PropertiesUtil.LEFT_SLANTING_BAR));
            configFilePath = path + File.separator + "config.properties";
        }
        Map<String, String> config = PropertiesUtil.getPrefixProperties(configFilePath, "config", "#");
        System.setProperty("webdriver.chrome.driver", config.get("chromeDriverPath"));
    }

    /**
     * 得到文件
     *
     * @param driver 司机
     * @return {@link Document}
     */
    private static Document getDocument(WebDriver driver) {
        String htmlContent = driver.getPageSource();
        return Jsoup.parse(htmlContent);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        //getAudiobookTitle();
        arrangeSeqTitle();
    }

    private static void arrangeSeqTitle() throws IOException {
        File file = new File(filePath);
        String text = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        String[] split = text.split("\r\n|\n");
        List<String> titleList = Arrays.stream(split).map(s -> {
            String[] s1 = s.split(" ");
            if (s1.length == 3) {
                String chapter = s1[1].replaceAll("第", "").replaceAll("集", "");
                String title = s1[2];
                return StringUtil.ratedLength(chapter, 4, "0", 0) + "." + title;
            }
            return "";
        }).collect(Collectors.toList());
        System.out.println(titleList);
    }

    /**
     * 获取有声书名
     *
     * @throws IOException          ioexception
     * @throws InterruptedException 中断异常
     */
    private static void getAudiobookTitle() throws IOException, InterruptedException {
        detectionEnvironment();
        options = new ChromeOptions();
        options.addArguments("--mute-audio");
        options.addArguments("--hide-scrollbars");
        options.addArguments("disable-infobars");

        driver = new ChromeDriver(options);

        driver.get(baseUrl);
        int totalPage = getTotalPage();
        List<String> titleList = getTitle(totalPage);
        String text = String.join("\n", titleList);
        OutputStream os = new FileOutputStream(filePath);
        IOUtils.write(text, os, StandardCharsets.UTF_8);
        Thread.sleep(100);
        driver.close();
    }

    /**
     * 获得标题
     *
     * @param totalPage 总页
     * @return {@link List<String>}
     * @throws InterruptedException 中断异常
     */
    private static List<String> getTitle(int totalPage) throws InterruptedException {
        List<String> titleList = new ArrayList<>(1400);
        for (int i = 1; i <= totalPage; i++) {
            driver.get(baseUrl+"p"+i);
            Document document = getDocument(driver);
            Elements textElements = document.getElementsByClass("sound-list").first().getElementsByClass("text");
            for (Element e : textElements) {
                String title = e.getElementsByTag("a").first().attr("title");
                titleList.add(title);
            }
        }
        return titleList;
    }

    /**
     * 得到总页数
     *
     * @return int
     */
    private static int getTotalPage() {
        Document document = getDocument(driver);
        Elements elements = document.getElementsByClass("page-link");
        Element element = elements.get(elements.size() - 2);
        String totalPage = element.getElementsByTag("span").first().text();
        return Integer.parseInt(totalPage);
    }

}
